#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int ticket=1000;
pthread_mutex_t lock;
void* routine(void* arg)
{
    int num=(int)arg;
    //准备抢票
    while(1)
    {
        pthread_mutex_lock(&lock);
        if(ticket>0)
        {
            
            printf("thread[%d] get ticket,left:%d\n",num,ticket--);
            pthread_mutex_unlock(&lock);
        }
        else 
        {
            pthread_mutex_unlock(&lock);
            break;
        }
    }
    return NULL;
}
int main(void)
{
    pthread_t tid[5];
    pthread_mutex_init(&lock,NULL);//对锁进行初始化
    for(int i=0;i<5;i++)//创建线程
    {
        pthread_create(&tid[i],NULL,routine,(void*)i);
    }
    for(int i=0;i<5;i++)//主线程等待线程join
    {
        pthread_join(tid[i],NULL);
    }
    printf("main thread over...\n");
    pthread_mutex_destroy(&lock);//销毁锁
    return 0;
}

